// 序列化和反序列化

#pragma once

#include "HttpServer.hpp"
#include "log.hpp"
#include "Util.hpp"
#include <vector>

const std::string SEP = "\r\n";
const std::string webRoot = "./webPage";          // web页面根目录，web目录中存放网页中的所有资源
const std::string defaultHomePage = "index.html"; // 默认首页，用户不能访问web目录本身，也不能访问web目录中的目录
const std::string wrongPage="./webPage/err_404.html";

class HttpRequest
{
public:
    HttpRequest() : _path(webRoot)
    {
    }
    ~HttpRequest()
    {
    }

    void Print()
    {
        logMessage(Debug, "method: %s, url: %s, version: %s",
                   _method.c_str(), _url.c_str(), _httpVersion.c_str());
        // for(const auto & line : body_)
        //     logMessage(Debug, "-%s", line.c_str());
        logMessage(Debug, "path: %s", _path.c_str());
        logMessage(Debug, "suffix_: %s", _suffix.c_str());
    }

public:
    std::string _method;            // 请求方法
    std::string _url;               // 路径
    std::string _httpVersion;       // 版本号
    std::vector<std::string> _body; // 有效载荷
    std::string _path;
    std::string _suffix; // 后缀 .jpg .mp3 .png等
};

// 将用户输入的message反序列化
HttpRequest Deserialize(std::string &message)
{
    HttpRequest req;
    std::string line = Util::ReadOneLine(message, SEP);
    Util::ParseRequestLine(line, &req._method, &req._url, &req._httpVersion);
    while (!message.empty())
    {
        line = Util::ReadOneLine(message, SEP);
        req._body.push_back(line);
    }
    req._path += req._url;
    if (req._path[req._path.size() - 1] == '/')
        req._path += defaultHomePage;

    auto pos = req._path.rfind(".");
    if (pos == std::string::npos)
        req._suffix = ".html"; // 找不到该后缀则返回默认界面
    else
        req._suffix = req._path.substr(pos); // 找到其他资源后缀
    return req;
}

std::string GetContentType(const std::string &suffix)
{
    std::string content_type = "Content-Type:";
    if (suffix == ".html" || suffix == ".htm")
        content_type + "text/html";
    else if (suffix == ".css")
        content_type += "text/css";
    else if (suffix == ".js")
        content_type += "application/x-javascript";
    else if (suffix == ".png")
        content_type += "image/png";
    else if (suffix == ".jpg")
        content_type += "image/jpeg";
    else
    {
    }
    return content_type + SEP;
}